package com.agentframework.core.agent;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangjun
 **/
public class DefaultReactStrategy implements ReactStrategy, InitializingBean, ApplicationContextAware {

    Map<String, ReactStrategy> reactStrategyMap = Collections.synchronizedMap(new HashMap<>());

    private ApplicationContext applicationContext;

    @Override
    public boolean react(Agent agent) {
        return reactStrategyMap.get(agent.getContext().getReactMode().getName()).react(agent);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, ReactStrategy> reactStrategyBeanMap = this.applicationContext.getBeansOfType(ReactStrategy.class);
        reactStrategyBeanMap.values().forEach(item -> reactStrategyMap.put(item.getClass().getName(), item));
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
